var ejs = require('ejs')
var fs = require('fs')
var path = require('path')
const request = require('request')
const qs = require('querystring')

templateDir = 'templates'
// var genFileName = 'nnsmk'
// var data = require('../templates/data/' + genFileName)
var filename = ''
var dirList = fs.readdirSync(templateDir)
var options = {}
var newFileName = ''
function main (data, isCover) {
  init(data)
  dirList.forEach(item => {
    if (item === 'data') {
      return
    }
    // 去掉模块名
    var tableDir = data.table.tableCameName.replace(data.moduleName, '')
    // 小驼峰
    tableDir = tableDir.replace(tableDir[0], tableDir[0].toLowerCase())
    if (item === 'service.ejs') {
      newFileName = 'src/api/' + data.moduleName + '/' + data.table.tableName.replace('_', '.').replace(/_/g, '') + '.service.js'
    } else if (item === 'details.ejs') {
      newFileName = 'src/view/modules/' + data.moduleName + '/' + tableDir + '/components/' + item.replace('.ejs', '.vue')
    } else if (item === 'search.ejs') {
      newFileName = 'src/view/modules/' + data.moduleName + '/' + tableDir + '/components/' + item.replace('.ejs', '.vue')
    } else if (item === 'handle-btns.ejs' || item === 'methods.ejs') {
      newFileName = 'src/view/modules/' + data.moduleName + '/' + tableDir + '/' + item.replace('.ejs', '.js')
    } else {
      newFileName = 'src/view/modules/' + data.moduleName + '/' + tableDir + '/' + item.replace('.ejs', '.vue')
    }
    if (!fs.existsSync(newFileName) || isCover) {
      console.log(newFileName + (isCover ? '被覆盖' : '文件不存在，正在创建....'))
      filename = templateDir + '/' + item
      // console.log(filename)
      ejs.renderFile(filename, data, options, function (err, str) {
        if (!err) {
          fs.writeFile(newFileName, str, {}, function (err) {
            if (err) {
              console.log(err)
            }
          })
        } else {
          console.log(err)
        }
      })
    } else {
      console.log(newFileName + '文件已存在，请先删除')
    }
  })
}
/**
 * 目录初始化
 */
function init (data) {
  // 去掉模块名
  var tableDir = data.table.tableCameName.replace(data.moduleName, '')
  // 小驼峰
  tableDir = tableDir.replace(tableDir[0], tableDir[0].toLowerCase())
  var apiDir = 'src/api/' + data.moduleName
  var viewDir = 'src/view/modules/' + data.moduleName + '/' + tableDir
  var componentsDir = 'src/view/modules/' + data.moduleName + '/' + tableDir + '/components'
  if (!fs.existsSync(apiDir)) {
    mkdirs(apiDir)
  }
  if (!fs.existsSync(viewDir)) {
    mkdirs(viewDir)
  }
  if (!fs.existsSync(componentsDir)) {
    mkdirs(componentsDir)
  }
}
/**
 * 创建多级目录
 * @param {} dirpath
 */
function mkdirs (dirpath) {
  if (!fs.existsSync(path.dirname(dirpath))) {
    mkdirs(path.dirname(dirpath))
  }
  fs.mkdirSync(dirpath)
}

var moduleName = process.argv[2]
var className = process.argv[3]
var isCover = process.argv[4] ? process.argv[4] === 1 : false

if (!moduleName || !className) {
  console.log(`两个参数:模块名 实体类名`)
  process.exit(1)
}

console.log(`模块名:${moduleName},实体类名:${className}`)
var paramsStr = qs.stringify({
  'group': '后台业务接口'
})
var requestParam = {
  url: `http://172.16.7.224:18080/v2/api-docs?${paramsStr}`
  // url: `http://localhost:18080/v2/api-docs?${paramsStr}`
}
request.get(requestParam, (err, response, body) => {
  console.info('statusCode:' + response.statusCode)
  if (!err) {
    var json = JSON.parse(body)
    if (!json.definitions[className]) {
      console.log(`实体类${className}不存在`)
      process.exit(1)
    }
    var genParams = buildGenerateParams(moduleName, className, json)
    main(genParams, isCover)
  } else {
    console.log(err)
    process.exit(1)
  }
})
function buildGenerateParams (moduleName, className, json) {
  var data = json.definitions[className]
  var param = json.definitions[className + 'Param']
  var tableCameName = className.replace(className[0], className[0].toLowerCase())
  var columns = []
  var reg = new RegExp('(\\d+)->(.+?)\\|([a-zA-Z_0-9]+?)[,)]', 'g')
  Object.keys(data.properties).forEach(item => {
    var obj = data.properties[item]
    if (['createTime', 'updateTime', 'isDeleted', 'searchMap', 'parentId', 'parentName'].findIndex(value => {
      return item === value
    }) === -1) {
      var required = false
      var isAdd = true
      if (param) {
        if (param.required) {
          // 是否必填
          required = param.required.findIndex(i => { return i === item }) !== -1
        }
        isAdd = param.properties.hasOwnProperty(item)
      }
      var remark = obj.description
      var formtype = 'text'
      var defaultValue = ''
      var items = []
      if (remark && isAdd) {
        while ((record = reg.exec(remark)) !== null) {
          items.push({
            'label': RegExp.$2,
            'value': RegExp.$1
          })
        }
        if (items.length) {
          defaultValue = items[0].value
          formtype = 'select'
          if (remark.indexOf('是否') !== -1) {
            formtype = 'radio'
          }
        }
        var index = remark.indexOf('(')
        if (index !== -1) {
          remark = remark.substr(0, index)
        }
        columns.push(
          {
            'primaryKey': item === 'id',
            'javaProperty': item,
            'formtype': item === 'id' ? 'none' : formtype,
            'remark': remark,
            'defaultValue': defaultValue,
            'searchable': true,
            'required': required,
            'show': true,
            'items': items
          }
        )
      }
    }
  })
  return {
    'moduleName': moduleName,
    'table': {
      'fullscreen': false,
      'labelWidth': 100,
      'remark': data.description ? data.description : className,
      'tableName': toLine(tableCameName),
      'className': className,
      'tableCameName': tableCameName,
      'columns': columns
    }
  }
}
// 驼峰转换下划线
function toLine (name) {
  return name.replace(/([A-Z])/g, '_$1').toLowerCase()
}
